package com.shinewind.sso.controller;

import cn.hutool.core.util.ObjectUtil;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.home.service.IUserInfoMappingService;
import com.shinewind.info.service.IUserDetailService;
import com.shinewind.info.service.IUserInfoService;
import com.shinewind.info.service.IUserRoleService;
import com.shinewind.pojo.dto.MyUserDto;
import com.shinewind.pojo.entity.UserDetail;
import com.shinewind.pojo.entity.UserInfo;
import com.shinewind.pojo.entity.UserInfoMapping;
import com.shinewind.pojo.entity.UserRole;
import com.shinewind.pojo.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/sso")
@Api(value = "用户注册", description = "用于用户注册")
public class RegisterController {
    @DubboReference
    private IUserInfoService iUserInfoService;
    @DubboReference
    private IUserInfoMappingService iUserInfoMappingService;
    @DubboReference
    private IUserRoleService iUserRoleService;
    @DubboReference
    private IUserDetailService iUserDetailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/model/register")
    @ApiOperation(value = "注册用户",notes = "注册",response = Result.class)
    public Result register(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        MyUserDto userDto = (MyUserDto) req.getAttribute("userDto");
        System.out.println("userDto:"+userDto);
        //判断账号是否已经被使用
        System.out.println("userDto:"+userDto);
        if(ObjectUtil.isNotNull(iUserInfoService.getUserInfoByUsername(userDto.getUserName()))){
            UserInfo userInfo1 = iUserInfoService.getUserInfoByUsername(userDto.getUserName());
            if(userInfo1.getUserName().equals(userDto.getUserName())) {
                return Result.fail(false, messageConstant.USERNAME_USED);
            }
        }
        //判断昵称是否被使用
        if(ObjectUtil.isNotNull(iUserInfoService.getUserInfoByNickname(userDto.getNickName()))){
            UserInfo userInfo2 = iUserInfoService.getUserInfoByNickname(userDto.getNickName());
            if(userInfo2.getNickName().equals(userDto.getNickName())) {
                return Result.fail(false, messageConstant.NICKNAME_USED);
            }
        }
        //判断电话是否被使用
        if(ObjectUtil.isNotNull(iUserInfoService.getUserInfoByTelephone(userDto.getTelePhone()))){
            UserInfo userInfo3 = iUserInfoService.getUserInfoByTelephone(userDto.getTelePhone());
            if(userInfo3.getTelePhone().equals(userDto.getTelePhone())) {
                return Result.fail(false, messageConstant.TELEPHONE_USED);
            }
        }

        return registerUser(userDto);
    }
    //注册用户
    @Transactional
    public Result registerUser(MyUserDto userDto) throws Exception {
        //将昵称、账号、加密的密码、电话存入userinfo表
        UserInfo saveUserInfo = UserInfo.builder().build();
        BeanUtils.copyProperties(userDto,saveUserInfo);
        saveUserInfo.setPassWord(new BCryptPasswordEncoder().encode(userDto.getPassWord()));
        UserInfo userInfo = iUserInfoService.insertANDGetUid(saveUserInfo);
        if(ObjectUtil.isNotNull(userInfo)){
            System.out.println("userInfo:"+userInfo);
            //将用户id映射存入userInfoMapping表
            iUserInfoMappingService.save(UserInfoMapping.builder().uId(userInfo.getUId()).build());
            //给用户默认的权限
            iUserRoleService.save(UserRole.builder().uId(userInfo.getUId()).role("ROLE_USER").build());
            //给用户添加默认的详细信息
            iUserDetailService.save(UserDetail.builder()
                    .uId(userInfo.getUId())
                    .sign("这个人很懒，还没有设置签名。")
                    .avatar("https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/0265a04fddbd77a19602a15d9d55d797.png~tplv-uwbnlip3yd-webp.webp")
                    .build());
            return Result.success(true,messageConstant.REGISTER_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.REGISTER_ERROR);
        }
    }

    //关闭浏览器时删除redis中存的用户token
    @PostMapping("/delete/user/token/{uId}")
    @ApiOperation(value = "删除redis中存的用户token",notes = "删除redis中存的用户token",response = Result.class)
    public void deleteToken(@PathVariable("uId") String uId){
        System.out.println("uid:"+uId);
        redisTemplate.delete(uId);
    }
}
